import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { SimpleAnimate } from '../../../share/animation/my.simple.animation';

import { HttpService } from '../../../share/http/http.service';
import { NoticeService } from '../../../share/service/notice.service';

import { User } from '../../../system/model/user.model';

import { TreeviewConfig, TreeviewItem, TreeItem } from 'ngx-treeview';

@Component({
  selector: 'hk-user-edit',
  templateUrl: './user.edit.component.html',
  styleUrls: ['./user.edit.component.css'],
  animations: [SimpleAnimate]
})
export class UserEditComponent implements OnInit {

  id: number;

  user: User = new User();

  showModal = false;
  imageUrl: string;

  // treeview的配置
  config = TreeviewConfig.create({
    hasAllCheckBox: false,
    hasFilter: false,
    hasCollapseExpand: false,
    decoupleChildFromParent: false,
    maxHeight: 400
  });

  items: TreeviewItem[] = [];

  reg = new RegExp(/^1(3[0-9]|4[57]|5[0-35-9]|7[0135678]|8[0-9])\d{8}$/);
  phoneNumberIsRepeated = false;

  constructor(
    private httpService: HttpService,
    private noticeService: NoticeService,
    private route: ActivatedRoute,
    private router: Router) { }


  ngOnInit() {
    this.getRoles();
    this.route.params.subscribe((params: Params) => {
      this.id = parseInt(params['id'], 10);
      if (this.id) {
        this.getById();
      }
    });

  }

  back() {
    this.router.navigate(['/main/user/list']);
  }

  save() {
    // 图片
    this.user.headPictureUrl = this.imageUrl;
    this.user.headPictureBase64 = this.imageUrl;
    let body = this.user;
    this.httpService.httpPostCallback('user/save', body, response => {
      if (response.errorCode === HttpService.SUCCESS) {
        this.noticeSuccess();
        this.back();
      } else {
        this.noticeService.error(response.errorMsg);
      }
    });
  }

  selectGoodsImage() {
    this.showModal = true;
  }

  pictureChange(event) {
    this.imageUrl = event;
  }

  onShowModalChange(event) {
    this.showModal = event;
  }

  onSelectedChange(event) {
    this.user.roleIds = event;
  }

  checkPhoneNumber() {
    if (this.user.phoneNumber && this.reg.test(this.user.phoneNumber)) {
      this.httpService.httpGetCallback('user/check/number/' + this.user.phoneNumber, response => {
        if (response.errorCode !== HttpService.SUCCESS) {
          this.phoneNumberIsRepeated = true;
        } else {
          this.phoneNumberIsRepeated = false;
        }
      });
    }
  }

  private getById() {
    this.httpService.httpGetSuccess('user/query/' + this.id, response => {
      this.user.setDataValue(response.data);
      this.imageUrl = this.user.headPictureUrl;
      this.checkRole(response.data.roleIds);
    });
  }

  private getRoles() {
    this.httpService.httpGetSuccess('role/list', response => {
      this.items = this.getItems(response.data);
      this.checkRole(this.user.roleIds);
    });
  }

  private getItems(roles: any[]): TreeviewItem[] {
    let treeviewItem: TreeviewItem[] = [];
    roles.forEach(role => {
      let item: TreeItem = {
        text: role.roleName,
        value: role.id,
        checked: false,
      };
      treeviewItem.push(new TreeviewItem(item));
    });
    return treeviewItem;
  }

  private checkRole(roleIds: number[]) {
    this.items.forEach(item => {
      roleIds.forEach(id => {
        if (id === item.value) {
          item.checked = true;
        }
      });
    });
  }

  private noticeSuccess() {
    if (this.id) {
      this.noticeService.success('保存成功');
    } else {
      this.noticeService.success('添加成功');
    }
  }

}
